import React from 'react';
import { WeaTools } from 'ecCom';

import ContainerView from './containerView';
import './style/';


export default class ContainerModle extends React.Component {

    state = {
        count: -1,
        tabId: 0,
        data: {
            id: '',
            setting: {
                title: '',
                showNumber: 5,
                styleId: 'template',
                tabWidthType: '0',
                tabWidth: '77',
                showTab: false,
                tabId: 0,
            },
            items: [],
            style: {},
            styles: [],
        }

    }

    componentWillMount() {
        this.onLoad();
    }

    setStateData = (data) => {
        this.setState(data);
    }


    onLoad = (callbackParams) => {
        const { id, javaInterface, onSaveBeforeHandler, onLoadFinallyHandler, layoutType, showSharing } = this.props;
        let { setting } = this.state.data;
        if(this.refs.ContainerViewProxy){
            this.refs.ContainerViewProxy.refs.ContainerView.refs.Element.onReflushStart()
        }

        let isFilterItems = layoutType == 'theme' && showSharing == true;
        WeaTools.callApi(javaInterface.find, 'GET', { json: JSON.stringify({ id }), isFilterItems }).then((result) => {
            if (result.data == null) {
                if (onSaveBeforeHandler) {
                    onSaveBeforeHandler(setting);
                }
                WeaTools.callApi(javaInterface.save, 'POST', { json: JSON.stringify({ id, setting: JSON.stringify(setting) }) }).then((result) => {
                    if (result.status == true) {
                        WeaTools.callApi(javaInterface.find, 'GET', { json: JSON.stringify({ id }), isFilterItems }).then((result) => {
                            this.setData(result);
                            this.setTabId(result);
                            if(result.tabId && result.tabId != ''){
                                this.setState({ tabId:result.tabId,data:result.data});
                            }else{
                                this.setState({ data:result.data});
                            }
                            if(this.refs.ContainerViewProxy){
                                this.refs.ContainerViewProxy.refs.ContainerView.refs.Element.onReflushEnd()
                            }
                        });
                    }
                });
            } else {
                this.setData(result, callbackParams);
                this.setTabId(result, callbackParams);
                if(result.tabId && result.tabId != ''){
                    this.setState({ tabId:result.tabId,data:result.data});
                }else{
                    this.setState({ data:result.data});
                }
                if (onLoadFinallyHandler) {
                    onLoadFinallyHandler();
                }
                if(this.refs.ContainerViewProxy){
                    this.refs.ContainerViewProxy.refs.ContainerView.refs.Element.onReflushEnd()
                }
            }
        });
    }


    setData = (result, callbackParams) => {
        const { onLoadAfterHandler, elementSettingProps = {} } = this.props;
        let data = Object.assign({}, { ...result.data });
        if (callbackParams && (callbackParams.handlerType == 'savaOrUpdateItem' || callbackParams.handlerType == 'deleteItem')) {
            data.setting = Object.assign({}, this.state.data.setting, elementSettingProps);
        } else {
            data.setting = Object.assign({}, JSON.parse(data.setting), elementSettingProps);
        }

        for (let i in data.items) {
            if (Object.prototype.hasOwnProperty.call(data.items, i)) {
                data.items[i].setting = JSON.parse(data.items[i].setting);
            }
        }
        for (let i in data.itemsForSetting) {
            if (Object.prototype.hasOwnProperty.call(data.itemsForSetting, i)) {
                data.itemsForSetting[i].setting = JSON.parse(data.itemsForSetting[i].setting);
            }
        }
        // 执行load后置处理器 校准数据
        if (onLoadAfterHandler) {
            if (onLoadAfterHandler.length == 1) {
                onLoadAfterHandler(data);
                result.data = data
            } else if (onLoadAfterHandler.length == 2) {
                onLoadAfterHandler(data, (data) => {
                    result.data = data
                });
            }
        } else {
            result.data = data
        }

        let pcsDom = $(`#portal-customElement-style-${data.id}`);
        if (pcsDom && pcsDom.length > 0) {
            pcsDom.html(data.style.css);
        } else {
            $($('head')[0]).append($(`<style id="portal-customElement-style-${data.id}" type="text/css">${data.style.css}</style>`));
        }
    }

    setTabId = (result, callbackParams) => {
        const { javaInterface, layoutType } = this.props;
        let { items, setting, id } = result.data;
        const { isremembertab, tabId } = setting;
        // if(isremembertab == 1 && tabId){
        //     this.setState({tabId})
        // }else if(items.length > 0){
        //     if(this.state.count == 0){
        //         this.setState({tabId:items[0].id})
        //         setting.tabId = items[0].id
        //         WeaTools.callApi(javaInterface.update, 'POST', {"json":JSON.stringify({id:id,setting:JSON.stringify(setting)})}).then((result) => {
        //         });
        //     }else{
        //         this.setState({tabId})
        //     }
        //
        // }
        if (callbackParams && ((callbackParams.handlerType == 'savaOrUpdateItem' && callbackParams.id == -1) || (callbackParams.handlerType == 'deleteItem' && !items.find(item => item.id == tabId))) && items.length > 0) {
            result.tabId = items[items.length - 1].id
            if (layoutType == 'theme') {
                setting.tabId = items[items.length - 1].id;
                WeaTools.callApi(javaInterface.update, 'POST', { json: JSON.stringify({ id, setting: JSON.stringify(setting) }) });
            }
        } else if (callbackParams && (callbackParams.handlerType == 'savaOrUpdateItem' || callbackParams.handlerType == 'tabChange') && callbackParams.id != -1) {
            result.tabId = callbackParams.id
            if (layoutType == 'theme') {
                setting.tabId = callbackParams.id;
                WeaTools.callApi(javaInterface.update, 'POST', { json: JSON.stringify({ id, setting: JSON.stringify(setting) }) });
            }
        } else if (layoutType == 'theme') {
            if (isremembertab == 0 && this.state.data.id == '' && items.length > 0) {
                result.tabId = items[0].id
                setting.tabId = items[0].id;
                WeaTools.callApi(javaInterface.update, 'POST', { json: JSON.stringify({ id, setting: JSON.stringify(setting) }) });
            } else {
                result.tabId = tabId
            }
        } else if (layoutType == 'login') {
            if (this.state.data.id == '' && items.length > 0) {
                result.tabId = items[0].id
            }
        }
    }


    tabsOnChange = (tabId) => {
        const { javaInterface, layoutType } = this.props;
        let { data } = this.state;
        const { id, setting } = data;

        if (layoutType == 'theme') {
            setting.tabId = tabId;
            WeaTools.callApi(javaInterface.update, 'POST', { json: JSON.stringify({ id, setting: JSON.stringify(setting) }) }).then(() => {
                this.onLoad({handlerType:'tabChange',id:tabId});
            });
        } else {
            this.onLoad({handlerType:'tabChange',id:tabId});
        }
    }

    hasIndex= (indexs, index) => {
        for (let i in indexs) {
            if (indexs[i].dataIndex == index) {
                return true;
            }
        }
        return false;
    }

    setSetting = (result,config) => {
        let { data } = this.state;
        let setting = Object.assign(data.setting, config);
        data.setting = setting;
        this.setState({ data });
    }

    render() {
        const { uuid, ContainerViewProxy, ContainerViewProxyByEcode } = this.props;
        let _ContainerViewProxy = null;
        if (ContainerViewProxyByEcode && window.rewritePortalCusEle && typeof rewritePortalCusEle == 'function') {
            _ContainerViewProxy = window.rewritePortalCusEle({ ...this.props, ContainerView, tabsOnChange: this.tabsOnChange, setStateData: this.setStateData, onLoad: this.onLoad, state: this.state }, { id: uuid, componentName: 'ContainerViewProxy' });
        }
        const {data,tabId } = this.state;
        const { id } = data;

        return (
            id ? (
                ContainerViewProxyByEcode ? (
                    _ContainerViewProxy
                ) : (
                    <ContainerViewProxy ecId={`${this && this.props && this.props.ecId || ''}_ContainerViewProxy@qpargq`} ref='ContainerViewProxy' {...this.props} ContainerView={ContainerView} tabsOnChange={this.tabsOnChange} setStateData={this.setStateData} onLoad={this.onLoad} state={this.state} />
                )
            ) : null

        );
    }
}
